package com.gx.components.motor2
{
	import com.gx.collision.Material;
	import com.gx.core.Component;
	import com.gx.events.TransformEvent;
	import com.gx.interfaces.IDrawable;
	import com.gx.interfaces.IPhysical;
	import com.gx.util.Raster;
	
	import de.polygonal.motor2.collision.shapes.BoxShape;
	import de.polygonal.motor2.collision.shapes.data.BoxData;
	import de.polygonal.motor2.collision.shapes.data.ShapeData;
	import de.polygonal.motor2.dynamics.RigidBody;
	import de.polygonal.motor2.dynamics.RigidBodyData;
	import de.polygonal.motor2.math.V2;
	
	import flash.display.Bitmap;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;

	public class BoxMotor2 extends Component implements IPhysical, IDrawable
	{
		
		private var _rigidBody:RigidBody;
		
		public var layer:PhysicsLayerM2;
		public var rectangle:Rectangle;
		public var color:uint = 0;
		public var material:Material = new Material(1);
		
		public function BoxMotor2()
		{
			super();
		}
		
		
		override public function init():void
		{
			var bData:RigidBodyData = new RigidBodyData();
			var shapeData:BoxData = new BoxData(material.density, rectangle.width, rectangle.height);
			bData.x = rectangle.x+rectangle.width/2;
			bData.y = rectangle.y+rectangle.height/2;
			bData.preventRotation = true;
			bData.addShapeData(shapeData);
			_rigidBody = layer.world.createBody(bData);
		}
		
		public function update():void
		{
			//var boxShape:BoxShape = _rigidBody.shapeList as BoxShape;
			var trans:Matrix = new Matrix(1,0,0,1,Math.floor(_rigidBody.x-rectangle.width/2),Math.floor(_rigidBody.y-rectangle.height/2));
			var e:TransformEvent = new TransformEvent(trans);
			this.dispatchEvent(e);
		}
		
		public function render(layer:Bitmap):void
		{
			if(visible)
			{
				_rigidBody.shapeList.toWorldSpace();
				var v:V2 = _rigidBody.shapeList.worldVertexChain;
				var vFirst:V2 = _rigidBody.shapeList.worldVertexChain;
				while(true)
				{
					
					if(v.last)
					{
						Raster.line(layer.bitmapData, v.x, v.y, vFirst.x, vFirst.y, color);
						break;
					}
					else
					{
						Raster.line(layer.bitmapData, v.x, v.y, v.next.x, v.next.y, color);
					}
					
					v = v.next;
				}
			}
			
		}
		
		private var _visible:Boolean;
		public function get visible():Boolean{return _visible;}
		public function set visible(value:Boolean):void{_visible = value;}
		
		
		
	}
}